/**
 * 基本信息
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { NoDataC, IconC, SecondHeaderC } from '../../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Spin } from 'antd';
import styles from './style.less';
import accounting from 'accounting';
import moment from 'moment';
import { namespace } from '@/src/newModels/leverageAnalysis/PortfolioManageLeverageAnalysisM';

@Form.create()
class BasicInfo extends PureComponent {
  state = {
    baseInfoData: undefined, // 基本信息数据
    averageLeverage: '', // 杠杆率标签数据
    productType: '', // 产品类型 1现金管理类，2开放式公募，3封闭式及其他
    labelSetData: [
      { productType: 1, highCriticalValue: '', middleCriticalValue: '', lowCriticalValue: '' },
      { productType: 2, highCriticalValue: '', middleCriticalValue: '', lowCriticalValue: '' },
      { productType: 3, highCriticalValue: '', middleCriticalValue: '', lowCriticalValue: '' },
    ],
  };

  componentDidMount() {
    if (this.props.searchData && this.props.searchData.portfolioCode) {
      this.getData(this.props.searchData);
      this.getLabelSetData();
      this.getLeverageDetailResults(
        JSON.parse(
          JSON.stringify(this.props.searchData)
            .replace(/beginDate/g, 'startDate')
            .replace(/timeRange/g, 'rangeType'),
        ),
      );
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.searchData) !== JSON.stringify(this.props.searchData)) {
      this.getData(nextProps.searchData);
      this.getLeverageDetailResults(
        JSON.parse(
          JSON.stringify(nextProps.searchData)
            .replace(/beginDate/g, 'startDate')
            .replace(/timeRange/g, 'rangeType'),
        ),
      );
    }
  }

  componentWillUnmount() {
    // 离开前清除models数据
  }

  // 获取echarts数据
  getData = (searchProps) => {
    const obj = {
      ...searchProps,
      startDate: moment(searchProps.beginDate).format('YYYY-MM-DD'),
      portfolioId: searchProps.portfolioCode,
      endDate: moment(searchProps.endDate).format('YYYY-MM-DD'),
    };
    delete obj.beginDate;
    delete obj.portfolioCode;
    delete obj.timeRange;
    this.props.dispatch({
      type: 'basicInfoInProM/getBasicInfoData',
      payload: { ...obj },
      callback: (type, res) => {
        if (type == 'success') {
          this.setState({
            baseInfoData: res,
          });
        }
      },
    });
  };

  // 数字类型数据处理-新
  changeNum = (text, dataType, fix, title) => {
    if (text === null || text === undefined) {
      return '--';
    } else if (dataType == 'rate') {
      // 比率类型
      if (title.indexOf('静态收益率') > -1 || title.indexOf('到期收益率') > -1 || title.indexOf('7日年化收益') > -1) {
        // 静态收益率、到期收益率、7日年化收益应直接%展示，不需要*100
        return `${Number(text).toFixed(fix)}%`;
      }
      return `${(Number(text) * 100).toFixed(fix)}%`;
    } else if (dataType == 'numb') {
      // 数额类型
      return accounting.formatNumber(Number(text), fix);
    }
  };

  // 获取杠杆率标签数据
  getLeverageDetailResults = (searchProps) => {
    const obj = {
      startDate: searchProps.startDate,
      endDate: searchProps.endDate,
      productcode: searchProps.portfolioCode,
    };
    this.props.dispatch({
      type: `${namespace}/queryLeverageDetailResults`,
      payload: { ...obj },
      callback: (res) => {
        this.setState({
          averageLeverage: res.dataSource[0].averageLeverage,
          productType: res.dataSource[0].productType,
        });
      },
    });
  };

  // 获取标签设置数据
  getLabelSetData = () => {
    this.props.dispatch({
      type: `${namespace}/queryLabelSetData`,
      payload: {},
      callback: (res) => {
        this.setState({
          newLabelSetData: [...res.dataSource],
        });
      },
    });
  };

  // 根据杠杆率高低进行页面显示
  judgeLeverageRatio = (title, averageLeverage, productType, newLabelSetData) => {
    if (title === '杠杆率(%)') {
      const newLabelSetDataDetail = newLabelSetData && newLabelSetData.find((item) => item.productType === productType);
      if (newLabelSetDataDetail) {
        const { highCriticalValue, lowCriticalValue, middleCriticalValue } = newLabelSetDataDetail;
        if (productType === '1') {
          if (averageLeverage >= highCriticalValue) {
            return (
              <>
                <span className={styles.itemTitle}>{title}</span>
                <span className={`${styles.leverageRatio} ${styles.leverageRatioHeigh}`}>高</span>
              </>
            );
          } else if (averageLeverage >= middleCriticalValue && averageLeverage < highCriticalValue) {
            return (
              <>
                <span className={styles.itemTitle}>{title}</span>
                <span className={`${styles.leverageRatio} ${styles.leverageRatioMedium}`}>中</span>
              </>
            );
          } else {
            return (
              <>
                <span className={styles.itemTitle}>{title}</span>
                <span className={`${styles.leverageRatio} ${styles.leverageRatioLow}`}>低</span>
              </>
            );
          }
        } else if (productType === '2') {
          if (averageLeverage >= highCriticalValue) {
            return (
              <>
                <span className={styles.itemTitle}>{title}</span>
                <span className={`${styles.leverageRatio} ${styles.leverageRatioHeigh}`}>高</span>
              </>
            );
          } else if (averageLeverage >= middleCriticalValue && averageLeverage < highCriticalValue) {
            return (
              <>
                <span className={styles.itemTitle}>{title}</span>
                <span className={`${styles.leverageRatio} ${styles.leverageRatioMedium}`}>中</span>
              </>
            );
          } else {
            return (
              <>
                <span className={styles.itemTitle}>{title}</span>
                <span className={`${styles.leverageRatio} ${styles.leverageRatioLow}`}>低</span>
              </>
            );
          }
        } else if (productType === '3') {
          if (averageLeverage >= highCriticalValue) {
            return (
              <>
                <span className={styles.itemTitle}>{title}</span>
                <span className={`${styles.leverageRatio} ${styles.leverageRatioHeigh}`}>高</span>
              </>
            );
          } else if (averageLeverage >= middleCriticalValue && averageLeverage < highCriticalValue) {
            return (
              <>
                <span className={styles.itemTitle}>{title}</span>
                <span className={`${styles.leverageRatio} ${styles.leverageRatioMedium}`}>中</span>
              </>
            );
          } else {
            return (
              <>
                <span className={styles.itemTitle}>{title}</span>
                <span className={`${styles.leverageRatio} ${styles.leverageRatioLow}`}>低</span>
              </>
            );
          }
        }
      }
    } else {
      return <span className={styles.itemTitle}>{title}</span>;
    }
  };

  // 数额类项渲染
  /**
   * title:标题
   * result:期末结果
   * changed:期初结果的变化值
   * type:1-正红，2-负绿
   * dataType:'rate'=比率  'numb'=数额
   * fix:精度
   */

  amountItemRend = (title, result, changed, type, dataType, fix, averageLeverage, productType, newLabelSetData) => {
    if (title === '杠杆率(%)') {
    }
    return (
      <div className={styles.itemBox}>
        <div style={{ flex: '1' }}>{this.judgeLeverageRatio(title, averageLeverage, productType, newLabelSetData)}</div>
        <div style={{ flex: '1', textAlign: 'right', marginRight: '20px' }}>
          <span className={styles.itemResult}>{this.changeNum(result, dataType, fix, title)}</span>
        </div>
        {type == '1' ? (
          // 正红
          <div style={{ flex: '1', textAlign: 'right', marginRight: '20px' }}>
            <span className={styles.itemChangeRed}>{this.changeNum(changed, dataType, fix, title)}</span>
            <IconC type={'upRegulate'} style={{ margin: '0 0 4px 4px', width: '12px', height: '12px' }} />
          </div>
        ) : type == '2' ? (
          // 负绿
          <div style={{ flex: '1', textAlign: 'right', marginRight: '20px' }}>
            <span className={styles.itemChangeGreen}>{this.changeNum(changed, dataType, fix, title)}</span>
            <IconC type={'downRegulate'} style={{ margin: '0 0 4px 4px', width: '12px', height: '12px' }} />
          </div>
        ) : (
          // 无数据
          <div style={{ flex: '1', textAlign: 'right', marginRight: '20px' }}>
            <span className={styles.itemNodata}>{this.changeNum(changed, dataType, fix, title)}</span>
            <div style={{ display: 'inline-block', width: '12px', height: '12px', margin: '0 0 4px 4px' }}></div>
          </div>
        )}
      </div>
    );
  };

  render() {
    const { baseInfoData, averageLeverage, productType, newLabelSetData } = this.state;
    return (
      <div className={styles.basicInfoContain} style={{ width: '100%', height: '100%' }}>
        {/* 基本信息 */}
        <SecondHeaderC title={'基本指标'} />
        <Spin spinning={this.props.loading.effects['basicInfoInProM/getBasicInfoData'] == true}>
          {baseInfoData && baseInfoData.length ? (
            <div className={styles.basicInfo}>
              <div className={styles.baseRow}>
                <div className={styles.basicTitle}>
                  <div></div>
                  <div>期末</div>
                  <div>较期初变动</div>
                </div>
                {baseInfoData &&
                  baseInfoData.map((item, index) => {
                    if (index > 5) return null;
                    return (
                      <div key={index} className={styles.basicItem}>
                        {this.amountItemRend(item.title, item.result, item.changed, item.type, item.dataType, item.fix, averageLeverage, productType, newLabelSetData)}
                      </div>
                    );
                  })}
              </div>
              <div className={styles.baseRow}>
                <div className={styles.basicTitle}>
                  <div></div>
                  <div>期末</div>
                  <div>较期初变动</div>
                </div>
                {baseInfoData &&
                  baseInfoData.map((item, index) => {
                    if (index < 6) return null;
                    return (
                      <div key={index} className={styles.basicItem}>
                        {this.amountItemRend(item.title, item.result, item.changed, item.type, item.dataType, item.fix)}
                      </div>
                    );
                  })}
              </div>
            </div>
          ) : (
            <NoDataC />
          )}
        </Spin>
      </div>
    );
  }
}
export default connect(({ basicInfoInProM, loading, profitOverviewM }) => ({
  basicInfoInProM,
  loading,
  profitOverviewM,
}))(BasicInfo);
